package com.tinem.platform.service.robot.im.core.plugin;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.service.robot.im.core.Message;
import com.tinem.platform.service.robot.im.core.ReplyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(100000)
public class OwnthinkChatRobotPlugin implements ApplicationListener<Message> {

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(Message event) {
        if(event.isEnd()){
            return;
        }
        String res = HttpUtil.get("https://api.ownthink.com/bot?appid=8f5a33feafe1ce5620389b35da49a614&userid="+event.getFromUser().getId()+"&spoken="+event.getContent());
        JSONObject r = JSON.parseObject(res);
        if(!r.getString("message").equals("success")){
            return;
        }
        event.setEnd(true);
        ReplyMessage replyMessage = new ReplyMessage(event);
        replyMessage.setContent(r.getJSONObject("data").getJSONObject("info").getString("text"));
        applicationContext.publishEvent(replyMessage);
    }
}
